import re
from utils.logger import log


class GlobalData():

    __set_global_var = {}

    def set_data(self,var,value):

        self.__set_global_var[var] = value
        log.info("Add variable data to global configuration: variable name is:{},value is:{}".format(var, value))
    
    def get_data(self):

        return self.__set_global_var

    # 解析字符串中全局变量并进行替换
    def resolve_global_var(self, pre_resolve_var, res=None, global_var_regex=r'\${.*?}'):
        var = self.__set_global_var
        if res and len(self.__set_global_var) != 0:
            for key, value in self.__set_global_var.items():
                if key not in res:
                    var[key] = value
        elif res:
            var = res

        re_global_var = re.compile(global_var_regex)

        def global_var_replace(match_obj):

            start_index = 2
            end_index = -1
            match_value = var.get(match_obj.group()[start_index:end_index])
            return match_value if match_value else match_obj.group()

        resolved_var = re.sub(pattern=re_global_var, string=pre_resolve_var, repl=global_var_replace)

        match = re.search(global_var_regex,pre_resolve_var)

        if pre_resolve_var == resolved_var and match is not None:

            log.error("Before string parsing:{},after string parsing:{}".format(pre_resolve_var,resolved_var))
            log.error("Variable not found:{},Please confirm whether to extract the variable".format(pre_resolve_var))
            return ''
        if pre_resolve_var != resolved_var:
            log.info("Before string parsing:{},after string parsing:{}".format(pre_resolve_var, resolved_var))
        return resolved_var


global_data = GlobalData()